//
//  UnFinishedOrderDetailViewController.m
//  FMJY
//
//  Created by 艾玩科技 on 17/4/10.
//  Copyright © 2017年 随心. All rights reserved.
//

#import "UnFinishedOrderDetailViewController.h"
#import "OrderFootView.h"
#import "ValuePickerView.h"
#import "UnFinishOrderHeadView.h"
#import "OrderFootView.h"
#import "UnFinishedOrderFootView.h"

@interface UnFinishedOrderDetailViewController ()<UITextViewDelegate,ChangeOverDelegate>

{
  
    
    NSMutableArray *driverInfoArr;//司机信息数组
    NSMutableArray *driverIdArr;//司机ID数组
    NSMutableArray *driverNameArr;//司机名字数组
    
    
    UITableView *unfinishTV;
    UnFinishOrderHeadView *headView;
    
    UnFinishedOrderFootView  *changeDriverFootView;
    
    //键盘将要显示时tableView的偏移量
    CGFloat contentoffy;
    
}

@property (nonatomic, strong) ValuePickerView *pickerView;
@end

@implementation UnFinishedOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"订单处理";
    
    
    //监听键盘显示和隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBordShowNotifitionCenter:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBordHidden) name:UIKeyboardWillHideNotification object:nil];

    unfinishTV = [[UITableView alloc] initWithFrame:CGRectMake(0, self.freeOrMoneyLabel.bottom, KScreenWidth, KScreenHeight - self.freeOrMoneyLabel.height - 64)];
    unfinishTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:unfinishTV];
    
    [unfinishTV reloadData];
    headView = [[[NSBundle mainBundle] loadNibNamed:@"UnFinishOrderHeadView" owner:nil options:nil] lastObject];
    unfinishTV.tableHeaderView = headView;
    
    
    
    
    //订单类型：收费 OR 免费
    if ([[_undealDataDic objectForKey:@"billingType"] integerValue] == 1) {
        
        self.freeOrMoneyLabel.text =@"该订单为：收费";
    }
    
    
    else if ([[_undealDataDic objectForKey:@"billingType"] integerValue] == 0)
    {
        self.freeOrMoneyLabel.text =@"该订单为：免费";
    }
//    订单编号，案件编号，订单来源，需救援车辆，需救援车牌
//    
//    orderNo  case_code insurName custCarDescr custCarPlate
    
    //服务类型
    headView.orderTypeLabel.text = [NSString stringWithFormat:@"服务类型：%@",[_undealDataDic objectForKey:@"helpTypeText"]];
    //订单编号
    headView.orderNumLabel.text =[NSString stringWithFormat:@"订单编号：%@",[_undealDataDic objectForKey:@"orderNo"]];
    //案件编号
    headView.anjianNumLabel.text =[NSString stringWithFormat:@"案件编号：%@",[_undealDataDic objectForKey:@"case_code"]];
    //订单来源
    headView.orderSourceLabel.text = [NSString stringWithFormat:@"订单来源：%@",[_undealDataDic objectForKey:@"insurName"]];
    //预估价格
    headView.yuguPriceLabel.text =[NSString stringWithFormat:@"预估价格：%@",[_undealDataDic objectForKey:@"one_price"]];
    //救援状态
    headView.orderStatueLabel.text = [NSString stringWithFormat:@"救援状态：%@",[_undealDataDic objectForKey:@"statusText"]];
    //救援司机
     headView.helpDriverLabel.text = [NSString stringWithFormat:@"救援司机：%@",[_undealDataDic objectForKey:@"driverName"]];
    //需救援车辆
    headView.needHelpCarLabel.text = [NSString stringWithFormat:@"需救援车辆：%@",[_undealDataDic objectForKey:@"custCarDescr"]];
    //需救援车辆的车牌号
    headView.carNumLabel.text = [NSString stringWithFormat:@"需救援车牌：%@",[_undealDataDic objectForKey:@"custCarPlate"]];
    
    
    //救援联系人姓名
    headView.helpNameLabel.text = [NSString stringWithFormat:@"救援联系人姓名：%@",[_undealDataDic objectForKey:@"custName"]];
    //汽车交付人电话
    headView.helpPhoneLabel.text =[NSString stringWithFormat:@"汽车交付人电话：%@",[_undealDataDic objectForKey:@"custPhone"]];
    //救援地址
    headView.helpAdressLabel.text = [NSString stringWithFormat:@"救援地址：%@",[_undealDataDic objectForKey:@"addr"]];
    
    
    //汽车签收人
    headView.carReceiveNameLabel.text = [NSString stringWithFormat:@"汽车签收人姓名：%@",[_undealDataDic objectForKey:@"destUser"]];
    headView.carReceiveTelLabel.text =[NSString stringWithFormat:@"汽车签收人电话：%@",[_undealDataDic objectForKey:@"destPhone"]];
    //拖车目的地
    headView.carReceiveAdressLabel.text =[NSString stringWithFormat:@"拖车目的地：%@",[_undealDataDic objectForKey:@"destAddr"]];
    

    
    

    driverIdArr = [[NSMutableArray alloc] init];
    driverNameArr =[[NSMutableArray alloc] init];
    driverInfoArr = [[NSMutableArray alloc] init];

    
    //服务商未分配给司机时
    if ([self.orderStatusNumStr integerValue] == 2030) {
        
        OrderFootView *driverFootView = [[[NSBundle mainBundle] loadNibNamed:@"OrderFootView" owner:nil options:nil] lastObject];
        [driverFootView.DriverArrivedBtn setTitle:@"接单" forState:UIControlStateNormal];
        [driverFootView.DriverArrivedBtn addTarget:self action:@selector(getOrderBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        unfinishTV.tableFooterView = driverFootView;
        
    }
    //改派
    else
    {
        
        NSMutableArray *nameArr = [NSMutableArray array];
        NSMutableArray *idArr = [[NSMutableArray alloc] init];
        //查询在线司机
        [CoreWork onlineDriverWithloginToken:GetUserLoginToken Block:^(id responsObject) {
            
#pragma mark -- 服务器报错  --
            if (![responsObject isKindOfClass:[NSDictionary class]]) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                
                return ;
                
                
            }
            
            
            //解析JSON数据
            [self dealResponse:responsObject];
            
            driverInfoArr = [responsObject objectForKey:@"data"];
            for (int i = 0; i <driverInfoArr.count; i ++)
            {
                [nameArr addObject:[driverInfoArr[i] objectForKey:@"name"]];
                [idArr addObject:[driverInfoArr[i] objectForKey:@"userId"]];
                changeDriverFootView= [[UnFinishedOrderFootView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
                changeDriverFootView.orderNumStrA = [NSString stringWithFormat:@"%@",[self.undealDataDic objectForKey:@"orderNo"]];
                changeDriverFootView.driverIDdArr = idArr;
                changeDriverFootView.driverNameArr =nameArr;
                changeDriverFootView.changeOverDelegateA = self;
                unfinishTV.tableFooterView = changeDriverFootView;
                
                changeDriverFootView.markTextViewM.delegate = self;
             
            }
            
        }];
      
     
    }
    
    
}


#pragma mark 键盘收起和展开时视图的frame
- (void)keyBordShowNotifitionCenter:(NSNotification *)notification{
    contentoffy = unfinishTV.contentOffset.y;
    
    
    
    unfinishTV.top = -200;
}
- (void)keyBordHidden{
    

    
    unfinishTV.top = self.freeOrMoneyLabel.bottom;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
//接单按钮的点击方法
- (void)getOrderBtnAct:(UIButton *)sender {
    
#pragma mark 提示音的播放与停止 代理方法
    if (self.PlayOrStopDelegateA && [self.PlayOrStopDelegateA respondsToSelector:@selector(playOrStop)]) {
        [self.PlayOrStopDelegateA playOrStop];
    }
    
    
    //查询在线司机
    [CoreWork onlineDriverWithloginToken:GetUserLoginToken Block:^(id responsObject) {

#pragma mark -- 服务器报错  --
        if (![responsObject isKindOfClass:[NSDictionary class]]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
            
            
        }
        
        
        //解析JSON数据
        [self dealResponse:responsObject];

        driverInfoArr = [responsObject objectForKey:@"data"];
        for (int i = 0; i <driverInfoArr.count; i ++)
        {
            [driverNameArr addObject:[driverInfoArr[i] objectForKey:@"name"]];
             [driverIdArr addObject:[driverInfoArr[i] objectForKey:@"userId"]];
       
        
        }

        
        self.pickerView = [[ValuePickerView alloc]init];

        self.pickerView.dataSource  = driverNameArr;
        self.pickerView.driverIDArr = driverIdArr;
        self.pickerView.pickerTitle = @"分配司机";
        __weak typeof(self) weakSelf = self;
        if (driverIdArr.count == 0) {
            
            return ;
        }
        self.pickerView.defaultStr = [NSString stringWithFormat:@"%@",driverIdArr[0]];
        self.pickerView.valueDidSelect = ^(NSString *value){
           
            
            [weakSelf.pickerView removeSelfFromSupView];
            
            //分配司机接口
            [CoreWork assignDriverWithorderNo:weakSelf.undealOrderNumStr  loginToken:GetUserLoginToken userDriverId:value Block:^(id responsObject) {
#pragma mark -- 服务器报错  --
                if (![responsObject isKindOfClass:[NSDictionary class]]) {
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                    
                    [alert addAction:sure];
                    [weakSelf presentViewController:alert animated:YES completion:nil];
                    
                    return ;
                    
                    
                }
                //解析JSON数据
                [weakSelf dealResponse:responsObject];
                //返回地图界面
                [weakSelf.navigationController popToViewController:[weakSelf.navigationController.viewControllers objectAtIndex:2] animated:YES];
                
            }];
          
            
        };
        [self.pickerView show];
        
        
    }];
    
    
   
    
    
    
    
}
#pragma mark 解析JSON数据
-(void)dealResponse:(NSDictionary *)responsObject
{

    
#pragma mark -- 报错 --
    if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == 0) ) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", [responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        
        return ;
    }
#pragma mark -- 账号在另一个地方登录，被迫退出 --
    else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == -3))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //调用退出接口
            [CoreWork logOutWithloginToken:GetUserLoginToken Block:^(id responsObject) {
//                 [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
                [self.navigationController presentViewController:[[LogInViewController alloc] init] animated:YES completion:nil];
            }];
            
        }];
        
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        
        return ;
    }
    

}
- (void)percentvaluechanggeEvent {
    
   
    
}

-(void)setUndealDataDic:(NSDictionary *)undealDataDic
{
    _undealDataDic = undealDataDic;
    
   
}
#pragma mark -- 改派成功后返回上一个界面 --
-(void)backToSuper
{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
